package com.common.frame.listener

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener

class SoftKeyBoardListener(activity: Activity?, listener: ListenerBuilder.() -> Unit) {
    private var mListener: ListenerBuilder = ListenerBuilder().also(listener)
    var rootViewVisibleHeight = 0
    var rootView = activity?.window?.decorView

    init {

        rootView?.viewTreeObserver?.addOnGlobalLayoutListener(OnGlobalLayoutListener {
            val rect = Rect()
            rootView?.getWindowVisibleDisplayFrame(rect)
            val visibleHeight = rect.height()
            if (rootViewVisibleHeight == 0) {
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }
            if (rootViewVisibleHeight == visibleHeight) {
                return@OnGlobalLayoutListener
            }
            if (rootViewVisibleHeight - visibleHeight > 200) {
                mListener.mKeyBoardShowAction?.invoke(rootViewVisibleHeight - visibleHeight)

                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }
            if (visibleHeight - rootViewVisibleHeight > 200) {
                mListener.mKeyBoardHideAction?.invoke(visibleHeight - rootViewVisibleHeight)
                rootViewVisibleHeight = visibleHeight
                return@OnGlobalLayoutListener
            }
        })


    }


    fun setListener(listenerBuilder: ListenerBuilder.() -> Unit) {
        mListener = ListenerBuilder().also(listenerBuilder)
    }

    inner class ListenerBuilder {
        internal var mKeyBoardShowAction: ((Int) -> Unit)? = null
        internal var mKeyBoardHideAction: ((Int) -> Unit)? = null

        fun keyBoardShow(action: (Int) -> Unit) {
            mKeyBoardShowAction = action
        }

        fun keyBoardHide(action: (Int) -> Unit) {
            mKeyBoardHideAction = action
        }
    }

}